<template>
  <div class="task-list" ref="taskListRef" @scroll="handleScroll" :style="{ width: width + 'px' }">
    <div class="task-list-content">
      <!-- 任务列表表头 -->
      <div class="task-list-header-row">
        <div 
          v-for="column in columns" 
          :key="column.key"
          class="task-cell"
          :class="[`task-${column.key}`, { 'sortable': column.sortable }]"
          :style="{ width: column.width + 'px' }"
          @click="column.sortable ? handleSort(column.key) : null"
        >
          <span>{{ column.label }}</span>
          <span v-if="column.sortable && sortField === column.key" class="sort-icon">
            {{ sortDirection === 'asc' ? '↑' : '↓' }}
          </span>
        </div>
        <!-- 列配置按钮 -->
        <div class="column-config-button" @click="showColumnConfig = true">
          <el-button type="text" size="small">
            <el-icon><Setting /></el-icon>
          </el-button>
        </div>
      </div>
      
      <!-- 任务列表 -->
      <div 
        v-for="task in sortedTasks" 
        :key="task.id"
        class="task-row"
        :class="{ 
          'sub-task': getTaskLevel(task) === 1,
          'sub-sub-task': getTaskLevel(task) === 2,
          'sub-task-level-3': getTaskLevel(task) === 3,
          'sub-task-level-4': getTaskLevel(task) >= 4
        }"
        @dblclick="handleTaskSelect(task)"
      >
        <div 
          v-for="column in columns" 
          :key="column.key"
          class="task-cell"
          :class="`task-${column.key}`"
          :style="{ width: column.width + 'px' }"
        >
          <!-- 任务名称列特殊处理 -->
          <div v-if="column.key === 'name'" class="task-name-content" :style="{ paddingLeft: getTaskLevel(task) * 20 + 'px' }">
            <!-- 展开/收缩按钮 -->
            <span 
              v-if="task && hasChildren(task)"
              class="expand-toggle"
              :class="{ 'expanded': !collapsedTasks.has(task.id) }"
              @click.stop="toggleTask(task.id)"
            >
              <svg class="expand-icon" viewBox="0 0 24 24" fill="currentColor">
                <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
              </svg>
            </span>
            <span v-else-if="task" class="expand-placeholder"></span>
            {{ task?.name || '未知任务' }}
          </div>
          
          <!-- 其他列使用渲染函数 -->
          <component 
            v-else-if="column.renderer"
            :is="column.renderer"
            :value="getTaskValue(task, column.key)"
          />
          <span v-else>{{ getTaskValue(task, column.key) }}</span>
        </div>
      </div>
    </div>

    <!-- 列配置对话框 -->
    <ColumnConfigDialog
      v-model="showColumnConfig"
      :columns="columns"
      :all-columns="allColumns"
      @save="handleColumnConfigSave"
    />
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import ColumnConfigDialog from './ColumnConfigDialog.vue'
import DateRenderer from './column-renderers/DateRenderer.vue'
import PriorityRenderer from './column-renderers/PriorityRenderer.vue'
import StatusRenderer from './column-renderers/StatusRenderer.vue'
import ProgressRenderer from './column-renderers/ProgressRenderer.vue'

export default {
  name: 'TaskList',
  components: {
    ColumnConfigDialog,
    DateRenderer,
    PriorityRenderer,
    StatusRenderer,
    ProgressRenderer,
    Setting
  },
  props: {
    tasks: {
      type: Array,
      required: true
    },
    columns: {
      type: Array,
      required: true,
      validator: (columns) => {
        return columns.every(col => 
          col.key && 
          col.label && 
          typeof col.width === 'number' &&
          typeof col.sortable === 'boolean'
        )
      }
    },
    width: {
      type: Number,
      default: 800
    },
    collapsedTasks: {
      type: Set,
      default: () => new Set()
    },
    // 新增：所有可用列定义
    allColumns: {
      type: Array,
      default: () => []
    }
  },
  emits: ['scroll', 'task-select', 'task-toggle', 'sort-change', 'columns-change'],
  setup(props, { emit }) {
    const taskListRef = ref(null)
    
    // 排序状态
    const sortField = ref('')
    const sortDirection = ref('asc')
    
    // 列配置对话框状态
    const showColumnConfig = ref(false)
    
    // 监听columns变化
    watch(() => props.columns, (newColumns) => {
      console.log('TaskList - columns props 变化:', newColumns)
      // 检查renderer属性
      newColumns.forEach(col => {
        console.log(`TaskList - 列 ${col.key} 的renderer:`, col.renderer)
        if (col.renderer) {
          console.log(`TaskList - 列 ${col.key} 的renderer类型:`, typeof col.renderer)
          console.log(`TaskList - 列 ${col.key} 的renderer名称:`, col.renderer.name)
        }
      })
    }, { deep: true })
    
    // 计算总宽度
    const totalWidth = computed(() => {
      return props.columns.reduce((sum, col) => sum + col.width, 0)
    })
    
    // 排序处理函数
    const handleSort = (field) => {
      console.log('排序字段:', field)
      if (sortField.value === field) {
        // 如果点击的是当前排序字段，切换排序方向
        sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
        console.log('切换排序方向:', sortDirection.value)
      } else {
        // 如果点击的是新字段，设置为升序
        sortField.value = field
        sortDirection.value = 'asc'
        console.log('设置新排序字段:', field, '方向:', sortDirection.value)
      }
      
      emit('sort-change', { field: sortField.value, direction: sortDirection.value })
    }
    
    // 列配置保存处理
    const handleColumnConfigSave = (newColumns) => {
      console.log('TaskList - 保存列配置:', newColumns)
      console.log('TaskList - 当前列配置:', props.columns)
      emit('columns-change', newColumns)
    }
    
    // 应用排序到任务列表
    const applySortToTasks = (taskList) => {
      if (!sortField.value) return taskList
      
      console.log('开始排序，字段:', sortField.value, '方向:', sortDirection.value)
      console.log('排序前任务列表:', taskList.map(t => `${t.name} (level: ${t.level}, parent: ${t.parentId})`))
      
      // 创建任务映射
      const taskMap = new Map()
      taskList.forEach(task => taskMap.set(task.id, task))
      
      // 按父任务分组同级任务
      const tasksByParent = {}
      const rootTasks = []
      
      taskList.forEach(task => {
        const parentId = task.parentId
        if (parentId) {
          if (!tasksByParent[parentId]) {
            tasksByParent[parentId] = []
          }
          tasksByParent[parentId].push(task)
        } else {
          rootTasks.push(task)
        }
      })
      
      // 排序函数
      const sortFunction = (a, b) => {
        let aValue = getTaskValue(a, sortField.value)
        let bValue = getTaskValue(b, sortField.value)
        
        // 处理不同类型的字段
        switch (sortField.value) {
          case 'startDate':
          case 'endDate':
            aValue = aValue?.valueOf() || 0
            bValue = bValue?.valueOf() || 0
            break
          case 'progress':
            aValue = aValue || 0
            bValue = bValue || 0
            break
          case 'priority':
            const priorityOrder = { high: 3, medium: 2, low: 1 }
            aValue = priorityOrder[aValue] || 0
            bValue = priorityOrder[bValue] || 0
            break
          case 'status':
            const statusOrder = { completed: 3, 'in-progress': 2, pending: 1 }
            aValue = statusOrder[aValue] || 0
            bValue = statusOrder[bValue] || 0
            break
          default:
            aValue = String(aValue || '').toLowerCase()
            bValue = String(bValue || '').toLowerCase()
        }
        
        if (sortDirection.value === 'asc') {
          return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
        } else {
          return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
        }
      }
      
      // 对根任务进行排序
      if (rootTasks.length > 1) {
        console.log('根任务数量:', rootTasks.length)
        rootTasks.sort(sortFunction)
        console.log('根任务排序后:', rootTasks.map(t => t.name))
      }
      
      // 对每个父任务下的子任务进行排序
      Object.keys(tasksByParent).forEach(parentId => {
        const tasks = tasksByParent[parentId]
        if (tasks.length > 1) {
          const parentTask = taskMap.get(parentId)
          console.log(`父任务 ${parentTask?.name || parentId} 的子任务数量:`, tasks.length)
          tasks.sort(sortFunction)
          console.log(`父任务 ${parentTask?.name || parentId} 的子任务排序后:`, tasks.map(t => t.name))
        }
      })
      
      // 重新构建任务列表，保持层级结构
      const result = []
      const processedTasks = new Set()
      
      // 递归添加任务及其子任务
      const addTaskWithChildren = (task) => {
        if (processedTasks.has(task.id)) return
        
        result.push(task)
        processedTasks.add(task.id)
        
        // 添加该任务的子任务
        const children = taskList.filter(t => t.parentId === task.id)
        children.forEach(child => {
          addTaskWithChildren(child)
        })
      }
      
      // 先处理根任务
      rootTasks.forEach(task => {
        addTaskWithChildren(task)
      })
      
      // 再处理其他级别的任务（保持原有顺序）
      taskList.forEach(task => {
        if (!processedTasks.has(task.id)) {
          addTaskWithChildren(task)
        }
      })
      
      console.log('排序后任务列表:', result.map(t => `${t.name} (level: ${t.level}, parent: ${t.parentId})`))
      return result
    }
    
    // 获取任务值
    const getTaskValue = (task, key) => {
      if (!task) return null
      return task[key]
    }
    
    // 计算任务的层级
    const getTaskLevel = (task) => {
      if (!task || !task.parentId) {
        return 0
      }
      
      let level = 0
      let currentTask = task
      
      // 递归计算层级
      while (currentTask.parentId) {
        level++
        currentTask = props.tasks.find(t => t.id === currentTask.parentId)
        if (!currentTask) {
          break
        }
      }
      
      return level
    }
    
    // 检查任务是否有子任务
    const hasChildren = (task) => {
      if (!props.tasks || props.tasks.length === 0) {
        return false
      }
      const children = props.tasks.filter(t => t.parentId === task.id)
      return children.length > 0
    }
    
    // 切换任务展开/收缩状态
    const toggleTask = (taskId) => {
      emit('task-toggle', taskId)
    }
    
    // 处理任务选择
    const handleTaskSelect = (task) => {
      emit('task-select', task)
    }
    
    // 处理滚动事件
    const handleScroll = (event) => {
      emit('scroll', event)
    }
    
    // 计算排序后的任务列表
    const sortedTasks = computed(() => {
      // 首先过滤任务（处理层级关系和收缩展开）
      const filtered = []
      
      // 安全检查
      if (!props.tasks || props.tasks.length === 0) {
        console.log('TaskList - 没有任务数据')
        return filtered
      }
      
      const shouldShowTask = (task) => {
        // 顶级任务总是显示
        if (task.level === 0) return true
        
        // 检查所有父级任务是否都展开
        let currentTask = task
        while (currentTask.parentId) {
          const parentTask = props.tasks.find(t => t.id === currentTask.parentId)
          if (!parentTask) {
            console.warn(`找不到父任务: ${currentTask.parentId} for task: ${task.id}`)
            return false
          }
          if (props.collapsedTasks.has(currentTask.parentId)) {
            console.log(`父任务 ${parentTask.name} 已收缩，隐藏子任务 ${task.name}`)
            return false
          }
          currentTask = parentTask
        }
        return true
      }
      
      // 递归函数：按层级顺序添加任务
      const addTasksInOrder = (parentId = null) => {
        // 找到所有以当前parentId为父级的任务
        const childTasks = props.tasks.filter(task => task.parentId === parentId)
        
        console.log(`查找parentId为 ${parentId} 的子任务:`, childTasks.map(t => `${t.name} (level: ${t.level})`))
        
        childTasks.forEach(task => {
          const shouldShow = shouldShowTask(task)
          console.log(`任务 ${task.name} (level: ${task.level}) 是否显示:`, shouldShow)
          
          if (shouldShow) {
            filtered.push(task)
            console.log(`添加任务: ${task.name} (level: ${task.level})`)
            // 递归添加子任务
            addTasksInOrder(task.id)
          } else {
            console.log(`隐藏任务: ${task.name} (level: ${task.level})`)
          }
        })
      }
      
      // 从顶级任务开始递归添加
      addTasksInOrder()
      
      console.log('TaskList - 任务数量:', props.tasks.length)
      console.log('TaskList - 过滤后任务数量:', filtered.length)
      console.log('TaskList - 收缩状态:', Array.from(props.collapsedTasks))
      
      // 然后应用排序
      return applySortToTasks(filtered)
    })
    
    return {
      taskListRef,
      sortField,
      sortDirection,
      totalWidth,
      sortedTasks,
      handleSort,
      getTaskValue,
      getTaskLevel,
      hasChildren,
      toggleTask,
      handleTaskSelect,
      handleScroll,
      showColumnConfig,
      handleColumnConfigSave
    }
  }
}
</script>

<style scoped>
.task-list {
  overflow-y: auto;
  overflow-x: hidden;
  border-right: 1px solid #d9d9d9;
  background: white;
  flex-shrink: 0;
}

.task-list-header-row {
  display: flex;
  background: #f0f0f0;
  border-bottom: 1px solid #d9d9d9;
  font-weight: 500;
  font-size: 12px;
  position: sticky;
  top: 0;
  z-index: 10;
  height: 50px;
  align-items: center;
  box-sizing: border-box;
}

.task-row {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  cursor: default;
  transition: background-color 0.2s;
  height: 50px;
  align-items: center;
  box-sizing: border-box;
}

.task-row:hover {
  background: #e6f7ff;
}

.task-row {
  position: relative;
}

.task-row::after {
  content: "双击编辑";
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 10px;
  color: #999;
  opacity: 0;
  transition: opacity 0.2s;
  pointer-events: none;
}

.task-row:hover::after {
  opacity: 1;
}

.task-row.sub-task {
  background: #f9f9f9;
}

.task-row.sub-sub-task {
  background: #f5f5f5;
}

.task-row.sub-task-level-3 {
  background: #f0f0f0;
}

.task-row.sub-task-level-4 {
  background: #e8e8e8;
}

.task-cell {
  display: flex;
  align-items: center;
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 8px;
  box-sizing: border-box;
  flex-shrink: 0;
}

.sortable {
  cursor: pointer;
  user-select: none;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 8px;
}

.sortable:hover {
  background-color: #e6f7ff;
}

.sort-icon {
  font-size: 12px;
  color: #409EFF;
  margin-left: 4px;
  font-weight: bold;
}

/* 任务名称内容样式 */
.task-name-content {
  display: flex;
  align-items: center;
  width: 100%;
}

/* 展开/收缩按钮样式 */
.expand-toggle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  margin-right: 6px;
  cursor: pointer;
  border-radius: 3px;
  transition: all 0.2s ease;
  color: #666;
  flex-shrink: 0;
}

.expand-toggle:hover {
  background-color: #e6f7ff;
  color: #409EFF;
  transform: scale(1.1);
}

.expand-toggle.expanded {
  color: #409EFF;
}

.expand-toggle.expanded:hover {
  background-color: #d1e7ff;
}

.expand-icon {
  width: 18px;
  height: 18px;
  transition: transform 0.2s ease;
}

.expand-toggle.expanded .expand-icon {
  transform: rotate(90deg);
}

/* 占位符样式 */
.expand-placeholder {
  width: 20px;
  margin-right: 6px;
  flex-shrink: 0;
}

/* 列配置按钮样式 */
.column-config-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border-left: 1px solid #d9d9d9;
  background: #f0f0f0;
  flex-shrink: 0;
}

.column-config-button .el-button {
  color: #409EFF;
  font-size: 16px;
  padding: 8px;
  border: none;
}

.column-config-button .el-button:hover {
  color: #66b1ff;
  background-color: #e6f7ff;
}
</style> 